package com.harmontronics.app.pedestal.db;

import android.database.Cursor;
import android.database.SQLException;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.Utils;
import com.harmontronics.app.pedestal.db.model.DaoMaster;
import com.harmontronics.app.pedestal.db.model.DaoSession;

public class CustomDBManager {
    private CustomDBManager() {
    }

    public static CustomDBManager getInstance() {
        return CustomDBManager.Holder.instance;
    }

    private static class Holder {
        private static CustomDBManager instance = new CustomDBManager();
    }

    private DaoSession mDaoSession;

    public Cursor execQuery(String database, String sql, String[] selectionArgs) {
        initDBConfig(database);
        return mDaoSession.getDatabase().rawQuery(sql, selectionArgs);
    }

    public void execSQL(String database, String sql) throws SQLException {
        initDBConfig(database);
        mDaoSession.getDatabase().execSQL(sql);
    }

    private void initDBConfig(String database) {
        if (!FileUtils.isFileExists(Utils.getApp().getDatabasePath(database))) {
            throw new IllegalArgumentException("数据库不存在");
        }

        CustomSQLiteOpenHelper openHelper = new CustomSQLiteOpenHelper(database);
        DaoMaster daoMaster = new DaoMaster(openHelper.getReadableDb());
        mDaoSession = daoMaster.newSession();
    }
}
